package com.niit.user_profile_center.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import com.niit.user_profile_center.mapper.FollowMapper;
import com.niit.user_profile_center.entity.User;


import javax.transaction.Transactional;


/**
 * 跟随服务类，提供用户关注、取消关注、检查关注状态和获取关注用户列表功能
 */
@Service
public class FollowService {
    /**
     * 跟随Mapper实例，用于执行数据库操作
     */
    @Autowired
    private FollowMapper followMapper;

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FollowService.class);




    /**
     * 使用给定的跟随Mapper初始化服务
     * 
     * @param followMapper 跟随Mapper实例
     */
    public FollowService(FollowMapper followMapper) {
        this.followMapper = followMapper;
    }

    /**
     * 用户关注另一个用户
     *
     * @param followerId  关注者ID
     * @param followingId 被关注者ID
     * @return 0=关注成功，-1=已关注，1=互相关注
     */
    @Transactional
    public int follow(Long followerId, Long followingId) {
        // 1. 判断是否已关注
        Boolean alreadyFollowed = followMapper.checkFollowStatus(followerId, followingId);
        if (Boolean.TRUE.equals(alreadyFollowed)) {
            return -1; // 已关注
        }

        // 2. 检查是否存在已删除的关注记录
        Boolean existsDeleted = followMapper.existsDeletedFollow(followerId, followingId);
        int result;

        if (Boolean.TRUE.equals(existsDeleted)) {
            // 恢复已删除记录，并设置 is_friend
            result = followMapper.restoreFollowAndSetFriend(followerId, followingId);
            logger.info("恢复关注关系: {} -> {}, is_friend = 1", followerId, followingId);
        } else {
            // 插入新记录，并设置 is_friend
            result = followMapper.followAndSetFriend(followerId, followingId);
            logger.info("新增关注关系: {} -> {}, is_friend = 1", followerId, followingId);
        }

        // 3. 判断是否互相关注
        Boolean isMutual = followMapper.checkFollowStatus(followingId, followerId);
        if (Boolean.TRUE.equals(isMutual)) {
            // 如果双方都关注了对方，则设置 is_friend = 1
            followMapper.updateIsFriend(followerId, followingId, 1);
            followMapper.updateIsFriend(followingId, followerId, 1);
            logger.info("互相关注成功，设置 is_friend = 1: {} <-> {}", followerId, followingId);
            return 1;
        }
        return 0;
    }
//    @Transactional
//    public int follow(Long followerId, Long followingId) {
//        // 1. 插入前先判断是否已关注
//        Boolean alreadyFollowed = followMapper.checkFollowStatus(followerId, followingId);
//        if (Boolean.TRUE.equals(alreadyFollowed)) {
//            return -1; // 已关注
//        }
//
//        // 2. 检查是否存在已删除的关注记录
//        Boolean existsDeleted = followMapper.existsDeletedFollow(followerId, followingId);
//        int result;
//
//        if (Boolean.TRUE.equals(existsDeleted)) {
//            // 如果存在已删除的记录，恢复它
//            result = followMapper.restoreFollow(followerId, followingId);
//        } else {
//            // 否则插入新的关注关系
//            result = followMapper.follow(followerId, followingId);
//        }
//
//        // 3. 判断是否互相关注
//        Boolean isMutual = followMapper.checkFollowStatus(followingId, followerId);
//        if (Boolean.TRUE.equals(isMutual)) {
//            // 互相关注即为好友（不需要额外操作，只是返回不同的状态码）
//            return 1;
//        }
//        return 0; // 关注成功但未互关
//    }
    // 判断A是否关注B


    public boolean isFriend(Long userId, Long otherId) {
        return followMapper.isFollowing(userId, otherId) > 0
                && followMapper.isFollowing(otherId, userId) > 0;
    }

    /**
     * 用户取消关注另一个用户
     * 
     * @param followerId  关注者ID
     * @param followingId 被关注者ID
     * @return 操作影响的行数
     */
//    public int unfollow(Long followerId, Long followingId){
//        return followMapper.unfollow(followerId, followingId);
//    }
    public int unfollow(Long followerId, Long followingId) {
        int result = followMapper.unfollowAndClearFriend(followerId, followingId);

        // 取消关注后，检查是否仍为互关（可能另一方还在关注）
        if (result > 0) {
            Boolean isStillMutual = followMapper.checkFollowStatus(followingId, followerId);
            if (!Boolean.TRUE.equals(isStillMutual)) {
                // 如果不再互关，将所有相关记录的 is_friend 设为 0
                followMapper.updateIsFriend(followerId, followingId, 0);
                followMapper.updateIsFriend(followingId, followerId, 0);
                logger.info("取消关注后不再互关，设置 is_friend = 0: {} <-> {}", followerId, followingId);

            }
        }
        return result;
    }




    public Boolean checkFollowStatus(Long followerId, Long followingId){
        return followMapper.checkFollowStatus(followerId, followingId);
    }
//    public boolean isFriend(Long userId, Long otherId) {
//        // 查询是否双方都有 is_friend = 1 的记录
//        return followMapper.isFriend(userId, otherId) > 0;
//    }

    public List<User> getFollowingUsers(Long userId) {
        return followMapper.getFollowingUsers(userId);
    }

    public List<User> getFollowers(Long userId) {
        return followMapper.getFollowers(userId);
    }
}